package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer socketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }


        // 校验地址和商家的距离
        checkOutOfRange(addressBook.getDetail());


        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
       // order.setStatus(Orders.PENDING_PAYMENT);
        //order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.TO_BE_CONFIRMED);
        order.setPayStatus(Orders.PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        //订单支付成功后 推送 消息给 商家端
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type",1) ;// 1为来单提醒 2为客户催单
        jsonObject.put("orderId",order.getId()) ;//
        jsonObject.put("content","订单号：" + order.getNumber());

        String messsage = jsonObject.toJSONString();
        socketServer.sendToAllClient(messsage);// 发送消息

        return orderSubmitVO;
    }

    @Value("${sky.baidu.ak}")
    private String ak;
    @Value("${sky.baidu.shopaddress}")
    private String shopAddress;


    private void checkOutOfRange(String detail) {
        // 1) 获取用户的坐标位置
        String url ="https://api.map.baidu.com/geocoding/v3";
        Map<String,String> param = new HashMap<>();
        param.put("address",detail);
        param.put("ak",ak);
        param.put("output","json");
        String jsonStr = HttpClientUtil.doGet(url, param);
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject jsonObject1 = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat1 = jsonObject1.getString("lat");
        String lng1 = jsonObject1.getString("lng");

        String useradd=lat1+","+lng1;
        // 2) 或商家位置
        param.put("address",shopAddress);
        String jsonStr2 = HttpClientUtil.doGet(url, param);
        JSONObject jsonObject2 = JSON.parseObject(jsonStr2);
        JSONObject jsonObject3 = jsonObject2.getJSONObject("result").getJSONObject("location");
        String lat2 = jsonObject3.getString("lat");
        String lng2 = jsonObject3.getString("lng");
        String shopadd=lat2+","+lng2;
        //3) 计算距离
        String url2="https://api.map.baidu.com/directionlite/v1/driving";
        Map<String,String> param2 = new HashMap<>();
        param2.put("origin",useradd);
        param2.put("destination",shopadd);
        param2.put("ak",ak);
        // 解析距离
        String jsonStr3 = HttpClientUtil.doGet(url2, param2);
        JSONObject jsonObject5 = JSON.parseObject(jsonStr3);
        JSONArray jsonArray = jsonObject5.getJSONObject("result").getJSONArray("routes");
        JSONObject object = (JSONObject)jsonArray.get(0);
        Object distance = object.get("distance");
        //4) 如果超出 5km 抛出异常
        if(Integer.parseInt(distance.toString())>5000){
            throw new AddressBookBusinessException("超出配送范围");
        }

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();


        orderMapper.update(orders);
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        //1. 设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize()); // 第几页,每页条数


        dto.setUserId(BaseContext.getCurrentId());
        //2. 条件查询订单信息
        Page<Orders> page= orderMapper.list(dto);
        List<Orders> ordersList = page.getResult();
        // 3,循环遍历第二步结果 查询订单明细
        List<OrderVO> orderVOList = new ArrayList<>();

        for (Orders orders : ordersList) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

            // 4.拼接VO
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO); // 复制同名属性
            orderVO.setOrderDetailList(orderDetailList);

            orderVOList.add(orderVO);
        }
        //5 返回数据
        return new PageResult(page.getTotal(),orderVOList);

    }

    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders =orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 拼接VO
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO); // 复制同名属性
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }


    /** 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 1) 查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //2) 遍历订单明细,生成购物车信息
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setId(null);// id 复制后 重置
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            // 2) 待确定: 购物车合并

            //3) 存储购物车
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        //1. 设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize()); // 第几页,每页条数

        //2. 条件查询订单信息
        Page<Orders> page= orderMapper.list(dto);
        List<Orders> ordersList = page.getResult();
        // 3,循环遍历第二步结果 查询订单明细
        List<OrderVO> orderVOList = new ArrayList<>();

        for (Orders orders : ordersList) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

            // 4.拼接VO
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO); // 复制同名属性
            //orderVO.setOrderDetailList(orderDetailList); //
            String dishNames=""; // 拼接菜品名字
            for (OrderDetail orderDetail : orderDetailList) {
                dishNames+=orderDetail.getName()+",";
            }
            orderVO.setOrderDishes(dishNames);

            orderVOList.add(orderVO);
        }
        //5 返回数据
        return new PageResult(page.getTotal(),orderVOList);
    }

    @Override
    public OrderStatisticsVO statistics() {
        //待接单数量
        // select count(*) from orders where status=?
        Integer toBeConfirmed =  orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        //待派送数量
        // select count(*) from orders where status=?
         Integer confirmed =  orderMapper.countByStatus(Orders.CONFIRMED);
        //派送中数量
        // select count(*) from orders where status=?
         Integer deliveryInProgress =  orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setConfirmed(confirmed);
        vo.setDeliveryInProgress(deliveryInProgress);
        vo.setToBeConfirmed(toBeConfirmed);

        return vo;
    }

    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.getById(id);

        // 发送催单提醒
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type",2) ;// 1为来单提醒 2为客户催单
        jsonObject.put("orderId",order.getId()) ;//
        jsonObject.put("content","订单号：" + order.getNumber());
        String messsage = jsonObject.toJSONString();
        socketServer.sendToAllClient(messsage);// 发送消息
    }

}
